import React, { DragEvent } from 'react'
import Widget from './Widget/index'
import ElementsModel from '@models/Elements'

import './index.css'

interface IProps {
  style: React.CSSProperties
}
interface IState {
  elements: Array<ElementsModel>
}

export default class Page extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props)
    this.state = {
      elements: [],
    }
  }
  render(): JSX.Element {
    return (
      <div
        className='page'
        style={this.props.style}
        onDrop={this.handleDrop.bind(this)}
        onDragOver={this.handleDragOver.bind(this)}
      >
        {this.state.elements.map((e: ElementsModel, idx: number) => (
          <Widget
            el={e}
            key={e.key + idx}
            onClick={(status) => this.handleWidgetClick(status, e.key)}
          />
        ))}
      </div>
    )
  }
  handleDragOver(event: DragEvent): void {
    event.preventDefault()
  }
  handleDrop(event: DragEvent): void {
    event.preventDefault()
    let data = event.dataTransfer!.getData('el')
    let obj = JSON.parse(data)
    this.setState({
      elements: [...this.state.elements, obj],
    })
  }
  handleWidgetClick(status: boolean, key: string): void {
    this.setState({
      elements: this.state.elements.map((el: ElementsModel) => {
        if (key !== el.key) return el
        else {
          el.selected = status
          return el
        }
      }),
    })
  }
}
